package com.cskaoyan.proxy;

import com.cskaoyan.service.UserService;
import com.cskaoyan.service.UserServiceImpl;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 注册service的代理组件
 * @author stone
 * @date 2021/12/27 17:15
 */
@Component
public class ServiceProxyFactoryBean implements FactoryBean<UserService> {
    @Autowired
    @Qualifier("userServiceImpl")
    UserService userService;
    @Override
    public UserService getObject() throws Exception {
        //可以使用jdk动态代理，也可以使用cglib动态代理
        Object proxy = Enhancer.create(UserServiceImpl.class, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("正道的光");
                method.invoke(userService, objects);
                System.out.println("照在大地上");

                return null;
            }
        });
        return (UserService) proxy;
    }

    @Override
    public Class<?> getObjectType() {
        return UserService.class;
    }
}
